(function(global){
    /**
     * 默认定时器参数. 
     */
    var _defaultConfig = {
        exeTimes : 0,
        maxTimes : Infinity,
        interval : 1000,
        timerFun : Function.empty
    };
    /**
     * 定时器构造函数. 
     * @param {Object} config.
     */
	var _Timer = function(config){
	    var _this = this;
	    this.config = Object.extend({}, _defaultConfig, config);
	    this.timerID = null;
	    //执行记录.
	    this.logList = [];
	    this.isStarted = false;
	    //任务包.
	    this.__timerFun = function(){
	        if(_this.config['maxTimes'] == _this.config['exeTimes']){
                _this.logList.push('Finished! Executed {0} times'.format(this.config['exeTimes']));
                return false;
            }
	        _this.logList.push('{0}: Start execute at {1}.'.format(++(_this.config['exeTimes']), Date.tick()));
	        _this.config['timerFun'].call(_this);
	        //默认是同步任务.
            if(_this.config['async'] !== true){
                _this.next();
            }            
	    };
	};
	/**
	 * 启动定时器. 
	 */
	_Timer.prototype.start = function(){
		this.end();
		this.__timerFun();		
	};
	/**
	 * 执行下一次任务. 
	 */
	_Timer.prototype.next = function(){
	    var _this = this;	    
        _this.timerID = (function(){
            _this.__timerFun.call(_this);
        }).defer(_this.config['interval']);
    };
	/**
	 * 终止定时器. 
	 */
	_Timer.prototype.end = function(){
		if(this.timerID){
			clearTimeout(this.timerID);
		}
	};
	/**
	 * 重置定时器. 
	 */
	_Timer.prototype.reset = function(){
        this.end();
        this.config['exeTimes'] = 0;
        this.timerID = null;
        this.logList = [];
    };
    /**
     * 打印任务日志. 
     */
    _Timer.prototype.printLog = function(){
        console.log(this.logList.join('\r\n'));
    };
    
    //----------------------------------------------------
    	
	ujs.define('Timer', 'ujs', function(){
        return _Timer;
    });
        
})(window);